package com.app.controller;


import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSONObject;
import com.app.model.Notice;
import com.app.service.INoticeService;
import com.app.util.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * <p>
 * 通知公告 前端控制器
 * </p>
 *
 * @author yoominic
 * @since 2025-02-27
 */
@Api(tags = "通知公告")
@RestController
@RequestMapping("/notice")
public class NoticeController {

    @Autowired
    private INoticeService noticeService;

    @ApiOperation(value = "获取通知公告列表", notes = "获取通知公告列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "limit", value = "每页数量", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "keyword", value = "搜索关键字", required = false, dataType = "String")
    })
    @GetMapping("/adminGetNoticeList")
    public Result adminGetNoticeList(Integer page, Integer limit, String keyword) {
        Page<Notice> noticePage = new Page<>(page, limit);

        QueryWrapper<Notice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        if (keyword != null && !keyword.equals("")) {
            queryWrapper.like("subject", keyword);
        }
        queryWrapper.orderByDesc("create_time");
        Page<Notice> noticeList = noticeService.page(noticePage, queryWrapper);
        JSONObject result = new JSONObject();
        result.put("total", noticeList.getTotal());
        result.put("list", noticeList.getRecords());
        return Result.success(result);
    }

    @ApiOperation(value = "保存通知公告", notes = "保存通知公告")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "notice", value = "通知公告对象", required = true, dataType = "Notice")
    })
    @PostMapping("/adminSaveNotice")
    public Result adminSaveNotice(@RequestBody Notice notice) {
        Integer loginUserId = StpUtil.getLoginIdAsInt();
        if (notice.getId() == null) {
            notice.setCreateId(loginUserId);
            notice.setStatus(1);
            notice.setCreateTime(LocalDateTime.now());
            noticeService.save(notice);
        }else {
            notice.setUpdateId(loginUserId);
            notice.setUpdateTime(LocalDateTime.now());
            noticeService.updateById(notice);
        }
        return Result.success("操作成功！");
    }

}

